package com.contactsconverter.activity;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONObject;

import com.contactsconverter.db.CTSIMDao;
import com.contactsconverter.model.CTContactModel;
import com.contactsconverter.model.CTNumberModel;
import com.contactsconverter.utils.CTUtils;
import com.contactsconverter.R;
import com.difsonapps.contacttranslator.dto.NumberDTO;
import com.difsonapps.contacttranslator.dto.NumberTypeEnum;

import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBarActivity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentProviderOperation;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.graphics.Paint;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

public class CTPaiementActivity extends ActionBarActivity {

	private ProgressDialog progressDialog;
	private List<CTContactModel> listOfContact;
	private int selectedTab;
	private int counter ;
	private int CREDIT ;
	private int nombreContactSelect ;
	private CTSIMDao cTSIMDao ;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_ctpaiement);
		counter = 0;
		Intent intent =  getIntent();
		int SELECTION_TAB = intent.getExtras().getInt(CTUtils.ARG_SELECTION_TAB);
		nombreContactSelect = 0;
		if(SELECTION_TAB == 0){
			nombreContactSelect  = intent.getExtras().getInt(CTUtils.ARG_PHONE_CONTACT_COUNT);
		}else
		{
			nombreContactSelect = intent.getExtras().getInt(CTUtils.ARG_SIM_CONTACT_COUNT);
		}
		TextView header1TextView = ((TextView)findViewById(R.id.tn_paiement_header));
		header1TextView.setText(String.format(getString(R.string.tn_paiement_header, nombreContactSelect)));
		
/*		TextView mtnHelptextView = ((TextView)findViewById(R.id.ct_paiement_mtnmoney_create_account));
		TextView orangeHelptextView = ((TextView)findViewById(R.id.ct_paiement_orangemoney_create_account));
		TextView cbHelptextView = ((TextView)findViewById(R.id.tn_paiement_carte_credit_create_account));
		TextView paypalHelptextView = ((TextView)findViewById(R.id.tn_paiement_paypal_create_account));
		final Intent hepIntent = new Intent(this, CTHelpActivity.class);
		mtnHelptextView.setPaintFlags(Paint.UNDERLINE_TEXT_FLAG);
		mtnHelptextView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startActivity(hepIntent);
			}
		});
		orangeHelptextView.setPaintFlags(Paint.UNDERLINE_TEXT_FLAG);
		orangeHelptextView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startActivity(hepIntent);
			}
		});
		cbHelptextView.setPaintFlags(Paint.UNDERLINE_TEXT_FLAG);
		cbHelptextView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startActivity(hepIntent);
			}
		});
		paypalHelptextView.setPaintFlags(Paint.UNDERLINE_TEXT_FLAG);
		paypalHelptextView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startActivity(hepIntent);
			}
		});
		(findViewById(R.id.ct_paiement_orangemoney)).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				payWithOrangeMoney(Uri.encode("#")+"199"+Uri.encode("#"));

			}
		});
		(findViewById(R.id.ct_paiement_mtnmoney)).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				payWithMtnMoney("*126*1"+Uri.encode("#"));

			}
		});
		(findViewById(R.id.tn_paiement_carte_credit)).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				//	Toast.makeText(getApplicationContext(), "Carte de credit", Toast.LENGTH_LONG).show();
				payWithCreditCard();

			}
		});
		(findViewById(R.id.tn_paiement_paypal)).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				//Toast.makeText(getApplicationContext(), "tn_paiement_paypal", Toast.LENGTH_LONG).show();
				payWithPayPal();

			}
		});

		Intent intent =  getIntent();
		int SELECTION_TAB = intent.getExtras().getInt(CTUtils.ARG_SELECTION_TAB);
		nombreContactSelect = 0;
		if(SELECTION_TAB == 0){
			nombreContactSelect  = intent.getExtras().getInt(CTUtils.ARG_PHONE_CONTACT_COUNT);
		}else
		{
			nombreContactSelect = intent.getExtras().getInt(CTUtils.ARG_SIM_CONTACT_COUNT);
		}

		TextView header1TextView = ((TextView)findViewById(R.id.tn_paiement_header));
		header1TextView.setText(String.format(getString(R.string.tn_paiement_header, nombreContactSelect)));

		String strCredit = CTUtils.getPreference(CTUtils.ARG_CREDIT, this);
		CREDIT = 0;
		try{
			CREDIT = Integer.parseInt(strCredit);

		}catch (Exception e) {
			CREDIT = 0;
		}

		TextView header2TextView = ((TextView)findViewById(R.id.tn_paiement_header1));
		header2TextView.setText(String.format(getString(R.string.tn_paiement_header1, CREDIT)));

		//TextView header3TextView = ((TextView)findViewById(R.id.tn_paiement_header2));
		if(nombreContactSelect > CREDIT)
			findViewById(R.id.tn_paiement_header_error).setVisibility(View.VISIBLE);
		else
			findViewById(R.id.tn_paiement_header_error).setVisibility(View.GONE);


		RadioButton radioButton1 = (RadioButton) findViewById(R.id.ct_paiement_cagnote1);
		radioButton1.setText(
				String.format(getString(R.string.ct_cagnote1),
						Integer.parseInt(getResources().getStringArray(R.array.ct_product_cost)[0])));
		
		RadioButton radioButton2 = (RadioButton) findViewById(R.id.ct_paiement_cagnote2);
		radioButton2.setText(
				String.format(getString(R.string.ct_cagnote2),
						Integer.parseInt(getResources().getStringArray(R.array.ct_product_cost)[1])));
*/
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		boolean showMenuView = getIntent().getBooleanExtra("SHOW_MENU_VIEW", true);

		if(showMenuView)
			getMenuInflater().inflate(R.menu.ctpaiement, menu);
		return true;
	}

	/*@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}*/

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		switch (id) {

		case android.R.id.home:
			Intent upIntent = NavUtils.getParentActivityIntent(this);
			upIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); 
			NavUtils.navigateUpTo(this, upIntent);
			return true;
		case R.id.tn_paiement_continue:
			//if(nombreContactSelect <= CREDIT){

				new AlertDialog.Builder(CTPaiementActivity.this)
				.setTitle(R.string.ct_paiement_confirm_header)
				.setMessage(String.format(getString(R.string.ct_paiement_confirm), nombreContactSelect))
				.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) { 
						
//						if(CTUtils.autoSynchroniseService != null){
//							
//							CTUtils.autoSynchroniseService.cancel(false);
//							CTUtils.autoSynchroniseService = null;
//						}
						
						if(CTContactsActivity.SELECTION_TAB == 0){
							selectedTab = CTContactsActivity.SELECTION_TAB;
							listOfContact = CTContactsActivity.contactModelList;
							new UpdateContacts().execute();
							//updateAll( CTContactsActivity.SELECTION_TAB, CTContactsActivity.contactModelList);
						}else{
							selectedTab = CTContactsActivity.SELECTION_TAB;
							listOfContact = CTContactsActivity.contactModelSimList;
							cTSIMDao = CTSIMDao.getINSTANCE(CTPaiementActivity.this);
							new UpdateContacts().execute();
							//updateAll( CTContactsActivity.SELECTION_TAB, CTContactsActivity.contactModelSimList);
						}

					}
				})
				.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {									
					}})
					.setIcon(android.R.drawable.ic_dialog_info)
					.show();

//
//			}else{
//
//				new AlertDialog.Builder(CTPaiementActivity.this)
//				.setTitle(R.string.ct_confirmer_dialog)
//				.setMessage(getString(R.string.ct_paiement_credit_insuffisant))
//				.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
//					public void onClick(DialogInterface dialog, int which) { 						
//					}
//				})
//
//				.setIcon(android.R.drawable.ic_dialog_alert)
//				.show();
//			}
			return true;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	private void payWithOrangeMoney(String phoneNumber){

		try {
			startActivityForResult(
					new Intent("android.intent.action.CALL", Uri.parse("tel:"
							+ phoneNumber)), 1);
		} catch (Exception eExcept) {
			Log.e(CTPaiementActivity.class.getName(), eExcept.getMessage());
		}

	}

	private void payWithMtnMoney(String phoneNumber){
		try {
			startActivityForResult(
					new Intent("android.intent.action.CALL", Uri.parse("tel:"
							+ phoneNumber)), 1);
		} catch (Exception eExcept) {
			Log.e(CTPaiementActivity.class.getName(), eExcept.getMessage());
		}
	}

	private void payWithPayPal(){
		Intent intent = new Intent(this, CTPayPalActivity.class);
		startActivity(intent);
	}

	private void payWithCreditCard(){
		Intent intent = new Intent(this, CTCarteCreditActivity.class);
		startActivity(intent);
	}

	private void updateContact(CTContactModel contact, int selectedTab){
		Uri contactsUri = ContactsContract.Contacts.CONTENT_URI;		
		if(selectedTab == 1){

			CTNumberModel ctNumberModel = contact.getNumbers().get(0);
			if(ctNumberModel.isCameroonian() && ctNumberModel.isConvertable()){
				contactsUri = Uri.parse("content://icc/adn"); 
				ContentValues values = new ContentValues();
				values.put("tag", contact.getName());  
				values.put("newTag", contact.getName());  
				values.put("number", ctNumberModel.getNumber());  		  
				values.put("newNumber", ctNumberModel.getConverterNumber());
				getContentResolver().update(contactsUri, values, null, null);
				ctNumberModel.setNumber(ctNumberModel.getConverterNumber());
				if(cTSIMDao != null)
					cTSIMDao.save(new NumberDTO(ctNumberModel.getNumber(), NumberTypeEnum.MOBILE));
				counter++;
			}
		}else{

			ArrayList<CTNumberModel> listOfNumber = contact.getNumbers();
			for (CTNumberModel ctNumberModel : listOfNumber) {

				if(ctNumberModel.isCameroonian() && ctNumberModel.isConvertable()){
				//	Log.e("IDIOT4 = ", ctNumberModel.toString());
					String where = ContactsContract.Data.CONTACT_ID + " = ? AND " + 
							ContactsContract.Data.MIMETYPE + " = ? AND " +
							String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE) + " = ? ";

					String[] params = new String[] {contact.getId()+"",
							ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
							String.valueOf(ctNumberModel.getNumberType())};				

					ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

					ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
							.withSelection(where, params)
							.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, ctNumberModel.getConverterNumber())
							.build());
					try {
						this.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
						ctNumberModel.setNumber(ctNumberModel.getConverterNumber());
						counter++;
					} catch (RemoteException e) {
						//e.printStackTrace();
					} catch (OperationApplicationException e) {					
						//e.printStackTrace();
					}
				}

			}
		}

		CTUtils.getProvider(CTPaiementActivity.this, contact);

		CTPaiementActivity.this.runOnUiThread(new Runnable() {
			public void run() {
				if(CTContactsActivity.SELECTION_TAB == 0){

					CTContactsActivity.mAdapter.notifyDataSetChanged();
				}else
					CTContactsActivity.mAdapterSim.notifyDataSetChanged();
			}});
		
		CTUtils.savePreference(CTUtils.ARG_CREDIT, (CREDIT - counter)+"", this);
	}



	private class UpdateContacts extends AsyncTask<Void, Void, Void>{		

		@Override
		protected void onPreExecute() {
			showProgress(true);
			super.onPreExecute();
		}
		@Override
		protected Void doInBackground(Void... params) {
			
			updateAll(selectedTab, listOfContact);
			return null;
		}
		private void updateAll(int selectedTab, List<CTContactModel> listOfContact){

			for (CTContactModel ctContactModel : listOfContact) {

				if (ctContactModel.isSelected() && (ctContactModel.getConvertCode()==Integer.valueOf(getString(R.string.to_converted_int)).intValue()||ctContactModel.getConvertCode()==Integer.valueOf(getString(R.string.notall_converted_int)).intValue())){
					updateContact(ctContactModel, selectedTab);
				}
			}


		}
		@Override
		protected void onPostExecute(Void result) {
			showProgress(false);
			CTPaiementActivity.this.finish();
			String toast = String.format(CTPaiementActivity.this.getString(R.string.notification_numero_convertis), counter);
			Toast.makeText(CTPaiementActivity.this, toast, Toast.LENGTH_LONG).show();
			super.onPostExecute(result);
		}

		private void showProgress(final boolean show) {


			if(show)
				progressDialog = ProgressDialog.show(CTPaiementActivity.this, "", "Loading...");
			else
				progressDialog.dismiss();
		}

	}
}
